package com.school.sports.entity.dto;

import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 统计数据传输对象
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StatisticsDTO {

    /**
     * 统计类型
     */
    private String statisticsType;

    /**
     * 统计时间范围开始
     */
    private LocalDateTime startTime;

    /**
     * 统计时间范围结束
     */
    private LocalDateTime endTime;

    /**
     * 总数量
     */
    private Long totalCount;

    /**
     * 今日数量
     */
    private Long todayCount;

    /**
     * 本周数量
     */
    private Long weekCount;

    /**
     * 本月数量
     */
    private Long monthCount;

    /**
     * 同比增长率
     */
    private BigDecimal yearOverYearGrowth;

    /**
     * 环比增长率
     */
    private BigDecimal monthOverMonthGrowth;

    /**
     * 统计详情列表
     */
    private List<Map<String, Object>> details;

    /**
     * 图表数据
     */
    private List<Map<String, Object>> chartData;

    /**
     * 统计项
     */
    private List<StatisticItem> items;

    /**
     * 生成时间
     */
    private LocalDateTime generatedAt;

    /**
     * 统计项内部类
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StatisticItem {
        private String name;
        private String value;
        private String unit;
        private String category;
        private BigDecimal percentage;
        private String color;
        private String icon;
        private String description;
        private Map<String, Object> extraData;

        public String getDisplayValue() {
            if (value == null) return "0";
            if (unit != null && !unit.trim().isEmpty()) {
                return value + " " + unit;
            }
            return value;
        }

        public String getDisplayPercentage() {
            if (percentage == null) return "0%";
            return percentage.multiply(new BigDecimal("100")) + "%";
        }
    }

    /**
     * 报名统计DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class EnrollmentStatisticsDTO {
        private Long totalEnrollments;
        private Long approvedEnrollments;
        private Long pendingEnrollments;
        private Long rejectedEnrollments;
        private Long todayEnrollments;
        private Map<String, Long> enrollmentsByProject;
        private Map<String, Long> enrollmentsByCollege;
        private Map<String, Long> enrollmentsByClass;
        private List<Map<String, Object>> dailyEnrollmentTrend;
        private List<Map<String, Object>> projectPopularityRanking;
    }

    /**
     * 成绩统计DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ScoreStatisticsDTO {
        private Long totalScores;
        private Long publishedScores;
        private Long pendingScores;
        private Long todayScores;
        private Map<String, Long> scoresByProject;
        private Map<String, Long> scoresByStatus;
        private List<Map<String, Object>> projectScoreDistribution;
        private List<Map<String, Object>> topPerformers;
        private List<Map<String, Object>> scoreRanges;
        private Map<String, BigDecimal> averageScoresByProject;
    }

    /**
     * 项目统计DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ProjectStatisticsDTO {
        private Long totalProjects;
        private Long activeProjects;
        private Long completedProjects;
        private Long upcomingProjects;
        private Map<String, Long> projectsByType;
        private Map<String, Long> projectsByGender;
        private Map<String, Long> projectsByStatus;
        private List<Map<String, Object>> projectPopularityRanking;
        private List<Map<String, Object>> enrollmentStatistics;
        private Map<String, Integer> averageParticipantsByType;
    }

    /**
     * 用户统计DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class UserStatisticsDTO {
        private Long totalUsers;
        private Long activeUsers;
        private Long students;
        private Long teachers;
        private Long referees;
        private Long volunteers;
        private Map<String, Long> usersByRole;
        private Map<String, Long> usersByCollege;
        private Map<String, Long> usersByGender;
        private List<Map<String, Object>> userRegistrationTrend;
        private List<Map<String, Object>> collegeUserDistribution;
    }

    /**
     * 志愿者统计DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class VolunteerStatisticsDTO {
        private Long totalVolunteers;
        private Long activeVolunteers;
        private Long totalApplications;
        private Long approvedApplications;
        private Long totalServiceHours;
        private Double averageServiceHours;
        private Map<String, Long> volunteersByDepartment;
        private Map<String, Integer> serviceHoursDistribution;
        private List<Map<String, Object>> topVolunteersByHours;
        private List<Map<String, Object>> volunteerActivityTrend;
        private Map<String, Long> tasksByType;
    }

    /**
     * 裁判统计DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class RefereeStatisticsDTO {
        private Long totalReferees;
        private Long activeReferees;
        private Map<String, Long> refereesByLevel;
        private Map<String, Long> refereesBySpecialty;
        private Long totalAssignments;
        private Long completedAssignments;
        private Map<String, Long> assignmentsByProject;
        private List<Map<String, Object>> refereeWorkloadRanking;
        private List<Map<String, Object>> refereePerformanceStatistics;
    }

    /**
     * 奖牌统计DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class MedalStatisticsDTO {
        private Long totalAwards;
        private Long goldMedals;
        private Long silverMedals;
        private Long bronzeMedals;
        private Map<String, Long> medalsByProject;
        private Map<String, Long> medalsByCollege;
        private Map<String, Long> medalsByClass;
        private List<Map<String, Object>> medalRankingByCollege;
        private List<Map<String, Object>> medalRankingByClass;
        private List<Map<String, Object>> projectMedalDistribution;
    }

    /**
     * 总体统计DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class OverviewStatisticsDTO {
        private Long totalParticipants;
        private Long totalProjects;
        private Long totalScores;
        private Long totalAwards;
        private Long totalVolunteers;
        private Long totalReferees;
        private LocalDateTime eventStartDate;
        private LocalDateTime eventEndDate;
        private Integer totalDays;
        private Map<String, Object> participantDemographics;
        private Map<String, Object> eventProgress;
        private List<Map<String, Object>> dailyActivitySummary;
        private Map<String, BigDecimal> participationRates;
    }

    /**
     * 时间序列数据DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class TimeSeriesDataDTO {
        private LocalDate date;
        private Long value;
        private String category;
        private String label;
        private BigDecimal changeRate;
        private Map<String, Object> metadata;

        public String getDisplayDate() {
            if (date == null) return "";
            return date.toString();
        }

        public String getDisplayValue() {
            if (value == null) return "0";
            return value.toString();
        }
    }

    /**
     * 排行榜数据DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class RankingDataDTO {
        private Integer rank;
        private String name;
        private String category;
        private Long value;
        private String unit;
        private String avatar;
        private String description;
        private Map<String, Object> details;

        public String getRankDisplay() {
            if (rank == null) return "-";
            switch (rank) {
                case 1: return "第" + rank + "名 🥇";
                case 2: return "第" + rank + "名 🥈";
                case 3: return "第" + rank + "名 🥉";
                default: return "第" + rank + "名";
            }
        }

        public String getDisplayValue() {
            if (value == null) return "0";
            if (unit != null && !unit.trim().isEmpty()) {
                return value + " " + unit;
            }
            return value.toString();
        }
    }

    /**
     * 图表配置DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ChartConfigDTO {
        private String chartType; // line, bar, pie, radar, etc.
        private String title;
        private List<String> xAxisLabels;
        private List<String> yAxisLabels;
        private List<Map<String, Object>> datasets;
        private Map<String, Object> options;
        private String colorScheme;

        public String getChartDisplayType() {
            if (chartType == null) return "柱状图";
            switch (chartType.toLowerCase()) {
                case "line": return "折线图";
                case "bar": return "柱状图";
                case "pie": return "饼图";
                case "radar": return "雷达图";
                case "area": return "面积图";
                case "scatter": return "散点图";
                default: return "柱状图";
            }
        }
    }

    /**
     * 导出配置DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ExportConfigDTO {
        private String exportType; // excel, pdf, csv, word
        private String templateName;
        private List<String> includedFields;
        private Map<String, Object> filters;
        private String fileName;
        private Boolean includeCharts;
        private Boolean includeHeaders;
        private String orientation; // portrait, landscape

        public String getFileExtension() {
            if (exportType == null) return ".xlsx";
            switch (exportType.toLowerCase()) {
                case "excel": return ".xlsx";
                case "pdf": return ".pdf";
                case "csv": return ".csv";
                case "word": return ".docx";
                default: return ".xlsx";
            }
        }
    }

    /**
     * 添加统计项
     */
    public void addStatisticItem(String name, String value, String unit, String category, BigDecimal percentage, String color, String icon, String description) {
        if (items == null) {
            items = new java.util.ArrayList<>();
        }
        items.add(new StatisticItem(name, value, unit, category, percentage, color, icon, description, null));
    }

    /**
     * 添加统计项（简化版本）
     */
    public void addStatisticItem(String name, String value, String unit) {
        addStatisticItem(name, value, unit, null, null, null, null, null);
    }

    /**
     * 获取统计项总数
     */
    public int getStatisticItemCount() {
        return items != null ? items.size() : 0;
    }

    /**
     * 检查是否有统计数据
     */
    public boolean hasStatisticData() {
        return items != null && !items.isEmpty();
    }

    /**
     * 检查是否有图表数据
     */
    public boolean hasChartData() {
        return chartData != null && !chartData.isEmpty();
    }

    /**
     * 获取时间范围显示
     */
    public String getTimeRangeDisplay() {
        if (startTime == null && endTime == null) {
            return "全部时间";
        } else if (startTime != null && endTime == null) {
            return startTime.toString().substring(0, 10) + " 至今";
        } else if (startTime == null && endTime != null) {
            return "至 " + endTime.toString().substring(0, 10);
        } else {
            return startTime.toString().substring(0, 10) + " 至 " + endTime.toString().substring(0, 10);
        }
    }

    /**
     * 获取生成时间显示
     */
    public String getGeneratedTimeDisplay() {
        if (generatedAt == null) return "未知";

        LocalDateTime now = LocalDateTime.now();
        long minutes = java.time.Duration.between(generatedAt, now).toMinutes();
        long hours = java.time.Duration.between(generatedAt, now).toHours();
        long days = java.time.Duration.between(generatedAt, now).toDays();

        if (minutes < 1) {
            return "刚刚";
        } else if (minutes < 60) {
            return minutes + "分钟前";
        } else if (hours < 24) {
            return hours + "小时前";
        } else if (days < 30) {
            return days + "天前";
        } else {
            return generatedAt.toString().substring(0, 10);
        }
    }
}